<template>
  <div style="height: 100%;">
    <div v-infinite-scroll="getList" :key="scrollKey"
         class="main"
         infinite-scroll-distance="100"
         :infinite-scroll-disabled="scrollDisabled">
      <div>
        <div class="work-log scroll-body">
          <div class="card">
            <flexbox class="hello-card">
              <XrAvatar :name="userInfo.realname" :size="50" :src="userInfo.img" class="user-img"/>
              <div class="greeting">
                <div class="hello">
                  {{ headData.timeLabel }}，{{ nickName }}
                  <span class="status">
                    <span :class="userDoneStatus.icon" class="icon wk"/>
                    <span>{{ userDoneStatus.label }}</span>
                  </span>
                </div>
                <div v-if="headData && headData.timeRemind" class="text">
                  {{ headData.timeRemind }}
                </div>
              </div>

              <div class="statistics">
                <div class="title">
                  <!-- <span class="icon wk wk-task" /> -->
                  <span>本月完成日志</span>
                </div>
                <div class="info">
                  <span class="special">{{ headData.allNum }}</span>篇
                </div>
              </div>
            </flexbox>
            <flexbox align="stretch" class="report-card">
              <div class="report-card__label">销售简报</div>
              <ReportMenu :list="reportList" @select="reportSelect"/>
            </flexbox>
          </div>
          <CreateLog v-if="showAdd" ref="createLogRef" class="add-card card"
                     @update="addLogSuccess"
                     @completeSelect="completeSelect"/>

          <flexbox class="filter-control card">
            <WkUserDepSelect v-if="showUserSelect"
                             :user-value.sync="filterForm.createUserId"
                             :dep-value.sync="filterForm.deptIds"
                             :props="{showSureBtn: true}"
                             placeholder="选择人员或部门"
                             @change="userDepChange"/>
            <TimeTypeSelect :width="190" :options="timeOptions" :default-type="timeSelect"
                            @change="timeTypeChange"/>
            <el-select v-model="filterForm.categoryId" placeholder="类型"
                       @change="refreshList">
              <el-option v-for="(item, index) in options" :key="index"
                         :label="item.label" :value="item.value"/>
            </el-select>
            <el-input v-model="search"
                      placeholder="请输入工作内容"
                      prefix-icon="el-icon-search"
                      type="text"
                      @blur="refreshList"
                      @keyup.enter="refreshList"/>
            <div class="filter-right">
              <span class="total-count">已筛选出<span>{{ totalCount }}</span>项</span>
              <el-button class="export-btn" @click="logExportClick">导出</el-button>
            </div>
          </flexbox>
        </div>

        <template v-for="(item, index) in listData" :key="index">
          <div class="card">
            <LogItem :data="item" :index="index" :show-history-btn="showUserSelect"
                     @read="handleRead(index)"
                     @add-comment="handleAddComment"
                     @delete="handleDelete"
                     @edit="handleEdit"
                     @relate-detail="enterRelateDetail"
                     @report-detail="reportSelect"
                     @check-history="checkUserHistory"/>
          </div>
        </template>
      </div>
      <p v-if="loading" class="scroll-bottom-tips">加载中...</p>
      <p v-if="noMore" class="scroll-bottom-tips">没有更多了</p>
    </div>
    <c-r-m-all-detail
        :visible.sync="showRelatedDetail"
        :crm-type="relatedCRMType"
        :id="relatedID"
        :no-listener-class="['content-item']"/>

    <NewDialog v-if="showNewDialog"
                :form-data="formData"
                :img-file-list="imgFileList"
                :accessory-file-list="accessoryFileList"
                :new-loading="newLoading"
                dialog-title="编辑日志"
                @close="showNewDialog = false"
                @submitBtn="submitEdit"/>

    <!-- 销售简报列表 -->
    <ReportList v-model:show="reportListShow"
        :title="reportData.title"
        :placeholder="reportData.placeholder"
        :crm-type="reportData.crmType"
        :request="reportData.request"
        :params="reportData.params"
        :record-request="reportData.recordRequest"
        :field-list="fieldReportList"
        :paging="reportData.paging"
        :sortable="reportData.sortable"/>

    <LogComDetail :show.sync="logComDetailShow" :type="logComDetailType"/>
  </div>
</template>

<script setup>
import {
  journalListAPI,
  journalEditAPI,
  journalQueryBulletinAPI,
  journalQueryRecordCountAPI,
  journalQueryBulletinByTypeAPI,
  journalGetLogWelcomeAPI,
  oaLogExportAPI
} from '/src/api/oa/journal.js'
import {crmQueryBulletinAPI} from '/src/api/crm/workbench.js'

import WkUserDepSelect from '/src/szcomponent/NewCom/SzDeptUserComp/WkUserDepSelect/index.vue'
import CRMAllDetail from '/src/views/crm/componentsNew/SzCrud/CRMAllDetail.vue'
import NewDialog from './components/NewDialog.vue'
import TimeTypeSelect from '/src/szcomponent/TimeTypeSelect/index.vue'
import ReportList from '/src/views/crm/workbench/components/ReportList/index.vue'
import ReportMenu from './components/ReportMenu.vue'
import LogItem from './components/LogItem.vue'
import CreateLog from './components/CreateLog.vue'
import LogComDetail from './components/LogComDetail.vue' // 日志完成 情况详情
import {useNumberHook} from "@/hooks/useNumberHook.js";

import moment from 'moment'
import {downloadExcelWithResData} from '/src/utils/index.js'
import {useErpUserStore} from "@/store/modules/usererp.js";
import {onBeforeRouteUpdate, useRoute, useRouter} from "vue-router"
import {useUserStore} from "@/store/modules/user.js";

const {separator} = useNumberHook();

defineOptions({
  name: 'WorkLog',
})

const optionData = reactive({
  logType: '', // all send 我发出的 received 我收到的
  // 头部信息
  headData: {
    nowNum: 0,
    allNum: 0,
    timeLabel: '',
    timeRemind: ''
  },

  // 简报信息
  reportList: [{
    type: 'customer',
    key: 'customerCount',
    info: '今日新增客户',
    name: '今日新增客户 0'
  }, {
    type: 'business',
    key: 'businessCount',
    info: '今日新增商机',
    name: '今日新增商机 0'
  }, {
    type: 'contract',
    key: 'contractCount',
    info: '今日新增合同',
    name: '今日新增合同 0'
  }, {
    type: 'receivables',
    key: 'receivablesMoney',
    info: '今日新增回款',
    name: '今日新增回款 0'
  }, {
    type: 'record',
    key: 'recordCount',
    info: '今日新增跟进记录',
    name: '今日新增跟进记录 0'
  }],
  // 简报信息


  listData: [],
  loading: false, // loading
  noMore: false,
  page: 1,
  totalCount: 0,
  scrollKey: Date.now(),

  options: [
    {label: '全部', value: 0},
    {label: '日报', value: 1},
    {label: '周报', value: 2},
    {label: '月报', value: 3}
  ],

  filterForm: {
    categoryId: 0,
    createUserId: [],
    deptIds: []
  },

  timeOptions: [
    {label: '今天', value: 'today'},
    {label: '昨天', value: 'yesterday'},
    {label: '本周', value: 'week'},
    {label: '上周', value: 'lastWeek'},
    {label: '最近30天', value: 'recent30'},
    {label: '最近60天', value: 'recent60'},
    {label: '本月', value: 'month'},
    {label: '上月', value: 'lastMonth'},
    {label: '本季度', value: 'quarter'},
    {label: '上季度', value: 'lastQuarter'},
    {label: '本年', value: 'year'},
    {label: '去年', value: 'lastYear'}
  ],
  timeSelect: {
    type: 'default',
    value: 'recent30'
  },
  search: '',

  // 相关详情的查看
  relatedID: '',
  relatedCRMType: '',
  showRelatedDetail: false,

  // 编辑
  newLoading: false,
  showNewDialog: false,
  formData: {},
  imgFileList: [],
  accessoryFileList: [],

  // 简报预览
  reportListShow: false,
  fieldReportList: null,
  reportData: {
    title: '',
    placeholder: '',
    crmType: '',
    request: null,
    recordRequest: journalQueryBulletinByTypeAPI,
    params: null,
    paging: true,
    sortable: false
  },

  // 日志完成详情
  logComDetailType: '',
  logComDetailShow: false
})

const {
  listData, loading, scrollKey, noMore, showRelatedDetail,
  showNewDialog, reportListShow, reportData, headData, reportList, filterForm, timeOptions,
  timeSelect, options, search, totalCount, formData, imgFileList, accessoryFileList,
  newLoading, fieldReportList, logComDetailShow, logComDetailType,
  relatedCRMType, relatedID
} = toRefs(optionData)

const createLogRef = ref();
onBeforeRouteUpdate((to, from, next) => {
  optionData.logType = to.params.type
  optionData.totalCount = 0
  if (createLogRef.value) {
    createLogRef.value.showMore = false
  }
  optionData.filterForm = {
    categoryId: 0,
    createUserId: [],
    deptIds: []
  }

  optionData.timeSelect = {
    type: 'default',
    value: 'recent30'
  }
  refreshList()
  next()
})


const userInfo = computed(() => {
  // const erpUserStore = useErpUserStore();
  const erpUserStore = useUserStore();

  return erpUserStore.userInfo
})

const showUserSelect = computed(() => {
  return optionData.logType != 'send'
})

const showAdd = computed(() => {
  return optionData.logType != 'received'
})

const userDoneStatus = computed(() => {
  return {
    icon: optionData.headData.nowNum > 0 ? 'wk-success' : 'wk-close',
    label: optionData.headData.nowNum > 0 ? '今天日志已完成' : '今天日志还未完成'
  }
})

// 无线滚动控制
const scrollDisabled = computed(() => {
  return optionData.loading || optionData.noMore
})

const nickName = computed(() => {
  if (!userInfo.value.realname) return userInfo.value.username
  const reg = /[a-zA-Z]+/
  if (reg.test(userInfo.value.realname) || !userInfo.value.sex) {
    return userInfo.value.realname
  }
  return userInfo.value.realname.slice(0, 1) + (userInfo.value.sex === 1 ? '先生' : '女士')
})

const route = useRoute()

function created() {
  optionData.logType = route.params.type
  optionData.logType = 'all'
  getLogRemind()
  getHeadDetail()
  getReportData()
}

created()

/**
 * 获取概要
 */
function getHeadDetail() {
  journalQueryBulletinAPI().then(res => {
    optionData.headData.nowNum = res.data.data.nowNum
    optionData.headData.allNum = res.data.data.allNum
  }).catch(() => {

  })
}

/**
 * 简报信息
 */
function getReportData() {
  optionData.loading = true
  console.log("userInfo", userInfo)
  crmQueryBulletinAPI({
    type: 'today',
    isUser: 1,
    userId: userInfo.value.id
  }).then(res => {
    optionData.loading = false
    // 注意，这里需要三个data，因为res.data.data的数据结构是{data, prev,receivablesMoney }
    const data = res.data.data.data || {}
    optionData.reportList = optionData.reportList.map(item => {
      if (item.key == 'receivablesMoney') {
        data.receivablesMoney = separator(Math.floor(data.receivablesMoney || 0))
      }
      item.name = `${item.info} ${data[item.key]}`
      return item
    })
  }).catch(() => {
    optionData.loading = false
  })
}

function getLogRemind() {
  getNetworkWelcome()
  const hour = moment().format('H')
  if (hour < 12) {
    // const num = Math.floor(Math.random() * 6)
    optionData.headData.timeLabel = '早上好'
    // this.headData.timeRemind = [
    //   '给自己一个微笑，告诉自己今天会更美好',
    //   '生命的意义在于和别人的不同之处',
    //   '美丽的早晨，灿烂的你，美好的一天在等你',
    //   '暖暖的阳光照，柔柔的轻风笑，绵绵的岁月长，真真的祝福到',
    //   '美好的一天开始了，每天给自己一个希望',
    //   '蓝天是宁静的，空气是清新的，阳光是明媚的'
    // ][num]
  } else if (hour < 18) {
    // const num = Math.floor(Math.random() * 6)
    optionData.headData.timeLabel = '下午好'
    // this.headData.timeRemind = [
    //   '认真对待工作，终有一天，你的每一份努力，都将绚烂成花',
    //   '通过辛勤的工作获得的财富才是人生的大快事',
    //   '生命之中总是有太多的感动，难忘的是你灿烂的笑容',
    //   '努力工作，永远不要向命运低头，不要向生活妥协',
    //   '生命，是一树花开，或安静或热烈',
    //   '人生，最快乐的莫过于奋斗'
    // ][num]
  } else {
    // const num = Math.floor(Math.random() * 5)
    optionData.headData.timeLabel = '晚上好'
    // this.headData.timeRemind = [
    //   '工作一天辛苦了，这世界不会辜负每一份努力和坚持',
    //   '无须缅怀昨天，不必奢望明天，只要认真过好每个今',
    //   '每一份坚持都是成功的累积，相信自己，总会遇到惊喜',
    //   '不要失去希望，你永远不知道明天会带来什么',
    //   '工作一天辛苦了，人生，最快乐的莫过于奋斗'
    // ][num]
  }
}

function getNetworkWelcome() {
  journalGetLogWelcomeAPI().then(res => {
    optionData.headData.timeRemind = res.data.data
  }).catch(() => {
  })
}

/**
 * 员工部门筛选change
 */
function userDepChange(userIds, deptIds) {
  optionData.filterForm.createUserId = userIds
  optionData.filterForm.deptIds = deptIds
  refreshList()
}

/**
 * 刷新列表
 */
function refreshList() {
  optionData.page = 1
  optionData.listData = []
  optionData.noMore = false
  optionData.totalCount = 0
  optionData.scrollKey = Date.now()
}

/**
 * 获取日志列表
 */
function getList(action = null) {
  if (optionData.loading) {
    return
  }
  optionData.loading = true
  const params = getBaseParams()
  params.page = optionData.page
  params.limit = 5

  journalListAPI(params).then(res => {
    optionData.loading = false
    if (!optionData.noMore) {
      optionData.listData = optionData.listData.concat(res.data.data.list)
      optionData.page++
    }
    optionData.totalCount = res.data.data.totalRow
    optionData.noMore = res.data.data.lastPage
  }).catch(() => {
    optionData.noMore = true
    optionData.loading = false
  })
}

/**
 * 获取基础请求参数
 */
function getBaseParams() {
  const params = {
    search: optionData.search,
    categoryId: optionData.filterForm.categoryId,
    createUserId: optionData.filterForm.createUserId.join(','),
    deptIds: optionData.filterForm.deptIds
  }

  if (optionData.timeSelect.type) {
    if (optionData.timeSelect.type === 'custom') {
      params.startTime = optionData.timeSelect.startTime.replace(/\./g, '-')
      params.endTime = optionData.timeSelect.endTime.replace(/\./g, '-')
    } else {
      params.type = optionData.timeSelect.value || ''
    }
  }

  if (optionData.logType != 'all') {
    params.by = {
      send: 1,
      received: 2
    }[optionData.logType]
  }

  if (optionData.logType == 'send' && params.hasOwnProperty('createUserId')) {
    delete params.createUserId
  }

  if (params.hasOwnProperty('categoryId') && params.categoryId === 0) {
    delete params.categoryId
  }

  return params
}

/**
 * 添加回复
 */
function handleAddComment(data) {
  optionData.listData[data.index].replyList.push(data.data)
}

/**
 * 日志删除
 * @param index {number}
 */
function handleDelete(index) {
  optionData.listData.splice(index, 1)
  getHeadDetail()
  refreshList()
}

/**
 * 日志添加成功
 */
function addLogSuccess() {
  refreshList()
  optionData.headData.nowNum++
  optionData.headData.allNum++
}

/**
 * 日志编辑
 * @param index {number}
 */
function handleEdit(index, data) {
  if (data.sendDeptList) {
    data.sendDeptList.forEach(item => {
      item.deptId = item.id
    })
  }
  optionData.formData = data
  optionData.imgFileList = data.img
  // 附件
  optionData.accessoryFileList = data.file
  optionData.showNewDialog = true
}

/**
 * 编辑提交
 */
function submitEdit(key, batchId, relevanceAll) {
  optionData.newLoading = true
  // 获取部门
  const dep = []
  if (optionData.formData.sendDeptList) {
    for (const j of optionData.formData.sendDeptList) {
      dep.push(j.id)
    }
  }
  // 获取员工
  const staff = []
  if (optionData.formData.sendUserList) {
    for (const h of optionData.formData.sendUserList) {
      staff.push(h.userId)
    }
  }

  const pramas = {
    logId: optionData.formData.logId,
    categoryId: key,
    content: optionData.formData.content,
    tomorrow: optionData.formData.tomorrow,
    question: optionData.formData.question,
    batchId: batchId,
    sendUserIds: staff.join(','),
    sendDeptIds: dep.join(','),
    customerIds: relevanceAll.customerIds.join(','),
    contactsIds: relevanceAll.contactsIds.join(','),
    businessIds: relevanceAll.businessIds.join(','),
    contractIds: relevanceAll.contractIds.join(',')
  }
  journalEditAPI(pramas).then(res => {
    optionData.showNewDialog = false
    refreshList()
    ElMessage.success({message: '编辑成功'})
    optionData.newLoading = false
  }).catch(() => {
    optionData.newLoading = false
    ElMessage.error({message: '编辑失败'})
  })
}

/**
 * 日志已读
 * @param index
 */
function handleRead(index) {
  optionData.listData[index].isRead = 1
}

/**
 * 查看某人历史
 */
function checkUserHistory(user) {
  console.log("checkUserHistory", user)
  if (user) {
    optionData.filterForm.createUserId = [user.userId]
  } else {
    optionData.filterForm.createUserId = []
  }
  refreshList()
}

/**
 * 时间更改
 */
function timeTypeChange(data) {
  optionData.timeSelect = data
  refreshList()
}

/**
 * 进入相关详情
 */
function enterRelateDetail(type, data) {
  optionData.relatedID = data.id
  optionData.relatedCRMType = type
  optionData.showRelatedDetail = true
}

/**
 * 简报预览
 */
function reportSelect(item, data) {
  console.log("reportSelect", item, data)
  if (item.type) {
    optionData.reportData.title = `销售简报-${item.info}`
    optionData.reportData.placeholder = {
      customer: '请输入客户名称',
      business: '请输入商机名称',
      contract: '请输入合同名称',
      receivables: '请输入回款编号',
      record: ''
    }[item.type]


    optionData.reportData.crmType = item.type
    // data 存在 是已添加日志预览  不存在为页面顶部 销售简报预览
    optionData.reportData.params = data ? {logId: data.logId} : {today: 1}

    // type   1 客户 2 商机 3 合同 4 回款 5 跟进记录
    optionData.reportData.params.type = {
      customer: 1,
      business: 2,
      contract: 3,
      receivables: 4,
      record: 5
    }[item.type]

    if (item.type == 'record') {
      optionData.fieldReportList = [{
        label: '模块',
        prop: 'crmType',
        width: 300
      }, {
        label: '新增跟进记录数',
        prop: 'count'
      }
      ]
      optionData.reportData.request = journalQueryRecordCountAPI
      optionData.reportData.paging = false
      optionData.reportData.sortable = false
    } else {
      optionData.fieldReportList = getReportFieldList(item.type)
      optionData.reportData.request = journalQueryBulletinByTypeAPI
      optionData.reportData.paging = true
      optionData.reportData.sortable = 'custom'
    }

    optionData.reportListShow = true
  }
}

/**
 * type   1 客户 2 商机 3 合同 4 回款 5 跟进记录
 *
 * 表头数据
 * 客户：客户名称、成交状态、最后跟进时间、创建时间、负责人
 * 商机：商机名称、商机阶段、最后跟进时间、创建时间、负责人
 * 合同：合同名称、合同状态、创建时间、公司签约人
 * 回款：回款编号、回款时间、负责人
 */
function getReportFieldList(type) {
  return {
    customer: [{
      label: '客户名称',
      prop: 'customerName'
    }, {
      label: '成交状态',
      prop: 'dealStatus'
    }, {
      label: '最后跟进时间',
      prop: 'lastTime'
    }, {
      label: '创建时间',
      prop: 'createTime'
    }, {
      label: '负责人',
      prop: 'ownerUserName'
    }],
    business: [{
      label: '商机名称',
      prop: 'businessName'
    }, {
      label: '商机阶段',
      prop: 'statusName'
    }, {
      label: '最后跟进时间',
      prop: 'lastTime'
    }, {
      label: '创建时间',
      prop: 'createTime'
    }, {
      label: '负责人',
      prop: 'ownerUserName'
    }],
    contract: [{
      label: '合同名称',
      prop: 'name'
    }, {
      label: '合同状态',
      prop: 'checkStatus'
    }, {
      label: '创建时间',
      prop: 'createTime'
    }, {
      label: '公司签约人',
      prop: 'companyUserName'
    }],
    receivables: [{
      label: '回款编号',
      prop: 'number'
    }, {
      label: '回款时间',
      prop: 'returnTime'
    }, {
      label: '负责人',
      prop: 'ownerUserName'
    }]
  }[type]
}

/**
 * 日志导出功能
 */
function logExportClick() {
  if (optionData.filterForm.categoryId == 0) {
    ElMessage.error({message: '请先选择”日报、周报、月报“中的一种类型导出'})
    return
  }

  optionData.loading = true

  oaLogExportAPI(getBaseParams()).then(res => {
    downloadExcelWithResData(res)
    optionData.loading = false
  }).catch(() => {
    optionData.loading = false
  })
}

/**
 * 查看完成信息
 */
function completeSelect(type) {
  optionData.logComDetailType = type
  optionData.logComDetailShow = true
}

</script>
<script>


// import {useErpUserStore} from "../../../store/modules/usererp.js";
import {mapState} from "pinia";

export default {
  // name: 'WorkLog',
  components: {
    // ReportMenu,
    // LogItem,
    // CreateLog,
    // LogComDetail,
    // WkUserDepSelect,
    // CRMAllDetail,
    // NewDialog,
    // TimeTypeSelect,
    // ReportList
  },
  data() {
    return {}
  },
  computed: {
    // ...mapGetters([
    //   'userInfo'
    // ]),
    // ...mapState(useErpUserStore, ['userInfo']),


  },
  watch: {},
  //
  // beforeRouteUpdate(to, from, next) {
  //   this.logType = to.params.type
  //   this.totalCount = 0
  //   if (this.$refs.createLog) {
  //     this.$refs.createLog.showMore = false
  //   }
  //   this.filterForm = {
  //     categoryId: 0,
  //     createUserId: [],
  //     deptIds: []
  //   }
  //
  //   this.timeSelect = {
  //     type: 'default',
  //     value: 'recent30'
  //   }
  //   this.refreshList()
  //   next()
  // },
  methods: {}
}
</script>

<style scoped lang="scss">
@import "style";
@import "/src/styles/iconfont/iconfont.css";
</style>
